<template>
  <d2-container>
    <el-main>
   
      <el-form ref="report" :model="report" label-width="80px" label-position="left"
               :rules="formRules">
                <el-form-item style="display: inline-block;position: absolute;top:10px;left:-30px" v-if="id != undefined">
                制表日期
                <el-date-picker :disabled='true'
                        v-model="report.date"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>
            <el-form-item style="display: inline-block;position: relative;top:10px;float: right;z-index: 100" v-if="id != undefined">
               <el-button type='primary' @click='exportExcel'>导出表格</el-button>
            </el-form-item>
        <el-row style='margin-top: 30px'>
        <el-form-item label="年份" prop="year" style="display: inline-block;width: 200px;">
          <el-input placeholder="年份" v-model="report.year" :disabled="disabled" type='number' step=1 @change='yearChange'></el-input>
        </el-form-item>
        <!-- <el-form-item label="周/月报" prop="gender" style="display: inline-block;margin-left: 50px"> -->
         <!--  <el-radio-group v-model="report.type" :disabled="disabled">
            <el-radio :label="0">周报</el-radio>
            <el-radio :label="1">月报</el-radio>
          </el-radio-group> -->
        <!-- </el-form-item> -->
         <el-form-item label="月份" prop="month" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="月份" v-model="report.month" :disabled="disabled" type='number' step=1 @change='monthChange' max='12'></el-input>
        </el-form-item >
        
        </el-form-item>
        
      </el-row>
      <el-row>
        <el-form-item label="报告人员" prop="name" style="display: inline-block;width: 200px;">
          <el-input placeholder="年份" v-model="report.staff.name" :disabled="true"></el-input>
        </el-form-item>
      
       <el-form-item label="手机" prop="cellphone" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="手机" v-model="report.staff.cellphone" :disabled="disabled"></el-input>
        </el-form-item>
      
       <el-form-item label="校长" prop="principlename" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="校长" v-model="report.principle.name" :disabled="disabled"></el-input>
        </el-form-item>
      
       <el-form-item label="校长手机" prop="principleCellphone" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="校长手机" v-model="report.principle.cellphone" :disabled="disabled"></el-input>
        </el-form-item>
      </el-row>

      </el-form>

      <el-table border style="width: 100%" :data='content' :span-method='cellMerge' >
      <el-table-column  label="" width="200" prop='name'>
       
      </el-table-column>
      <el-table-column  label="上月计划">
        <template slot-scope='scope'>
          <textarea v-model='scope.row.content[0]' style="width: 100%;height: 100px" :disabled='disabled' v-if="scope.$index == 0">
          </textarea>
          <input  v-model='scope.row.content[0]' style="width: 100%;height: 30px" :disabled='disabled' v-if="scope.$index != 0">
          </input>
        </template>
      </el-table-column >
      <el-table-column  label='本月计划'>
        <template slot-scope='scope'>
          <textarea v-model='scope.row.content[1]' style="width: 100%;height: 100px" :disabled='disabled' v-if="scope.$index == 0">
          </textarea>
           <input  v-model='scope.row.content[1]' style="width: 100%;height: 30px" :disabled='disabled' v-if="scope.$index != 0">
          </input>
        </template>
      </el-table-column >
      <el-table-column  label='上月完成情况'>
        <template slot-scope='scope'>
          <textarea v-model='scope.row.content[2]' style="width: 100%;height: 100px"  :disabled='disabled' v-if="scope.$index == 0">
          </textarea>
           <input  v-model='scope.row.content[2]' style="width: 100%;height: 30px" :disabled='disabled' v-if="scope.$index != 0">
          </input>
        </template>
      </el-table-column>
      
      
    </el-table>

    <h4>新开班情况<el-button @click='addClass' style='margin-left: 10px' :disabled='disabled'>添加班级</el-button></h4>
    <el-table  :data='newClasses'>
           <el-table-column label='班级名称'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.name" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='已报名人数'>
             <template slot-scope='scope' >
                
                 <input  v-model="scope.row.studentAmount" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='新生数'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.newStudent" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='转卡人数'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.convert" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='转卡率'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.convertRate" :disabled="disabled"></input>
             </template>
           </el-table-column>
           </el-table-column>
            <el-table-column  label='操作'>
        <template slot-scope='scope'>
         <el-button @click='deleteClass(scope.$index)' :disabled='disabled'>删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <h4>员工月创收<el-button @click='addStaff' style='margin-left: 10px' :disabled='disabled'>添加员工</el-button></h4>
    <el-table  :data='staffIncome'>
           <el-table-column label='老师'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.name" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='月创收（元)'>
             <template slot-scope='scope'>
                 <input  v-model="scope.row.total" :disabled="disabled"></input>
             </template>
           </el-table-column>
           <el-table-column label='带班人数'>
             <template slot-scope='scope' >
                 <input  v-model="scope.row.number" :disabled="disabled"></input>
             </template>
            
           </el-table-column>
            <el-table-column  label='操作'>
        <template slot-scope='scope'>
         <el-button @click='deleteStaff(scope.$index)' :disabled='disabled'>删除</el-button>
        </template>
      </el-table-column>
          
    </el-table>

        <h4>财务预算</h4>
        <textarea v-model='finance' style="width:70%;min-height: 100px" :disabled='disabled'></textarea>
        <h4>上月工作总结</h4>
        <textarea v-model='summary' style="width:70%;min-height: 100px" :disabled='disabled'></textarea>

    </el-main>
    <el-footer style="text-align: center">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="edit" v-show="id != undefined">修改</el-button>
    </el-footer>
  </d2-container>
</template>

<script>
import request from "@/plugin/axios"
import {mapState} from "vuex"
import formatTime from '@/libs/util.formatTime'
import excel from '@/libs/util.excel'
export default {
  data() {
    return {
      report :{
        type : 0,
        year : new Date().getFullYear(),
        month : new Date().getMonth() + 1,
        week : 1,
        staff : {name:'',cellphone:''},
        principle : {name:'',cellphone:''},
        date : formatTime.formatDate(String(new Date())),
        id : undefined
      },
      content : [{name:'团队目标',content:['','','']},{name:'出勤率',content:['','','']},{name:'续报率',content:['','','']},{name:'招生',content:['','','']}],
      weeks : [],
      editShow: false,
      disabled: false,
      newClasses : [],
      staffIncome :[],
      id: undefined,
      monthlabel1 : 'x月计划（本月',
      monthlabel2 : 'x月计划（上月)',
      monthlabel3 : 'x月完成情况（上月)',
      schoolList: [],
      finance : '',
      summary : '',
      formRules: {
        name: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        
         date: [
          {required: true, message: '请选择制表时间', trigger: 'blur'},
          
        ],
      
      },
    };
  },
  computed:{
    ...mapState('d2admin/user',['info'])
  },
  methods: {
    cellMerge({row,column,rowIndex,columnIndex}){

      return {
        colspan : 1,
        rowspan : 1
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    edit() {
      this.disabled = false;
    },
   
    submit() {
      if (this.report.year < 2019){
        this.$alert('','请输入正确年份')
        return false
      }
      if (this.staff == null){
        this.$alert('','请先绑定员工再重新登录')
        return false
      }
      let data = {};
      data.staff = this.staff
      data.principle = this.report.principle.name
      data.cellphone = this.report.staff.cellphone
      data.principleCellphone = this.report.principle.cellphone
      data.school = this.school
      data.type = this.report.type
      data.year = this.report.year
      data.month = this.report.month
      data.staffIncome = this.staffIncome
      data.finance = this.finance
      data.content = this.content
      data.newClasses = this.newClasses
      data.summary = this.summary
      let url = "/data/newMonthReport";
      if (this.id != undefined) {
        data.id = this.id;
        url = "/data/updateMonthReport";
      }
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.report = {type : 0,
        year : new Date().getFullYear(),
        month : new Date().getMonth() + 1,
        week : 1,
        staff : {name:'',cellphone:''},
        principle : {name:'',cellphone:''},
        date : formatTime.formatDate(String(new Date())),
        id : undefined}
        this.content = [{name:'团队目标',content:['','','']},{name:'出勤率',content:['','','']},{name:'续报率',content:['','','']},{name:'招生',content:['','','']}]
        this.finance = ''
        this.summary = '' 
        this.newClasses = []
        this.staffIncome = []
          this.$router.push({path: "/report-list"})
          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
        // 返回数据
      });
    },

    deleteClass(index){
      this.newClasses.splice(index,1)
    },

    deleteStaff(index){
      this.staffIncome.splice(index,1)
    },
    addClass(){
      this.newClasses.push({name:'',convert:undefined,newStudent:0,studentAmount:0,convertRate:0})
    },

    addStaff(){
      this.staffIncome.push({name:'',number:undefined,total:undefined,id:undefined})
    },
    getReportOne(id) {
      request({
        url: "/data/getMonthReport",
        method: "post",
        data: {id: id}
      }).then(res => {
        if (res.code == 200) {
          this.report.staff = res.data.staff
          this.report.principle.name = res.data.principle
          this.report.staff.cellphone = res.data.cellphone
          this.report.principle.cellphone = res.data.principleCellphone
          // this.school =data.school
          this.report.year = res.data.year
          this.report.month = res.data.month
          this.staffIncome = res.data.staffIncome
          this.newClasses = res.data.newClasses
          this.content = res.data.content
          this.finance = res.data.finance
          this.summary = res.data.summary
        }
      });
    },

    exportExcel(){
      let output = []
      let merge = []
      output.push(['制表日期',this.report.date])
      output.push(['年份',this.report.year,'月份',this.report.month])
      output.push(['报告人员',this.report.staff.name,'手机',this.report.staff.cellphone,'校长',this.report.principle.name,'校长手机',this.report.principle.cellphone])
      output.push([''])
      output.push(['','上月计划','','','本月计划','','','上月完成情况','',''])
      merge.push({s:{r:4,c:1},e:{r:4,c:3}})
      merge.push({s:{r:4,c:4},e:{r:4,c:6}})
      merge.push({s:{r:4,c:7},e:{r:4,c:9}})

      output.push (['团队目标',this.content[0].content[0],'','',this.content[0].content[1],'','',this.content[0].content[2],'',''])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      output.push (['出勤率',this.content[1].content[0],'','',this.content[1].content[1],'','',this.content[1].content[2],'',''])
      output.push (['续报率',this.content[2].content[0],'','',this.content[2].content[1],'','',this.content[2].content[2],'',''])
      output.push (['招生',this.content[3].content[0],'','',this.content[3].content[1],'','',this.content[3].content[2],'',''])
      merge.push({s:{r:5,c:0},e:{r:7,c:0}})
      merge.push({s:{r:5,c:1},e:{r:7,c:3}})
      merge.push({s:{r:5,c:4},e:{r:7,c:6}})
      merge.push({s:{r:5,c:7},e:{r:7,c:9}})

      merge.push({s:{r:8,c:1},e:{r:8,c:3}})
      merge.push({s:{r:8,c:4},e:{r:8,c:6}})
      merge.push({s:{r:8,c:7},e:{r:8,c:9}})
      merge.push({s:{r:9,c:1},e:{r:9,c:3}})
      merge.push({s:{r:9,c:4},e:{r:9,c:6}})
      merge.push({s:{r:9,c:7},e:{r:9,c:9}})
      output.push(['',''])
      output.push(['',''])
      output.push(['新开班情况'])
      output.push(['班级名称','报名人数','新生数','转卡人数','转卡率'])

      for (var i =0  ;i < this.newClasses.length ; i++){
        output.push([this.newClasses[i].name,this.newClasses[i].studentAmount,this.newClasses[i].newStudent,this.newClasses[i].convert,this.newClasses[i].convertRate])
      }
      output.push(['',''])
      output.push(['',''])
      output.push(['员工月创收'])
      output.push(['老师','月创收（元）','带班人数'])

      for (var i =0  ;i < this.staffIncome.length ; i++){
        output.push([this.staffIncome[i].name,this.staffIncome[i].total,this.staffIncome[i].number])
      }

      output.push(['',''])
      output.push(['财务预算'])
      output.push([this.finance])
      output.push(['',''])
      output.push(['',''])
      output.push(['',''])
      output.push(['',''])
      
      let len = output.length
      merge.push({s:{r:len - 1,c:0},e:{r:len + 4,c:10}})
      output.push(['',''])
      output.push(['上月工作总结'])
      output.push([this.summary])
      output.push(['',''])
      output.push(['',''])
      output.push(['',''])
      output.push(['',''])
      merge.push({s:{r:len + 7, c:0},e:{r:len + 11,c:10}})
      excel.exportRaw(output,this.report.year + '年' + this.report.month + '月' + this.info.school[0].name + '月报',merge)
    },

    monthChange(){
      this.loadData()
    },
    yearChange(){
      this.loadData()

    },
    
    loadData(){
      let data ={}
      data.month = this.report.month
      data.year = this.report.year
      data.school = this.school
      data.type = 'month'
       request({
        url: "/data/getMonthReportData",
        method: "post",
        data: data
      }).then(res => {
        if (res.code == 200){
          this.classData = res.data.newClasses
          this.content[1].content[2] = res.data.coursePercentage
          this.content[2].content[2] = (res.data.actualContinueNumber || 0) / (res.data.suppoedContinueNumber || 1)
          this.staffIncome = res.data.teacherIncome
          this.content.push('')
          this.content.splice(this.content.length - 1,1)
          this.newClasses = res.data.newClasses
          for(var i = 0;i < this.newClasses.length ;i++){
            this.newClasses[i].convertRate = parseFloat((this.newClasses[i].convert || 0) / (this.newClasses[i].newStudent || 1) * 100).toFixed(2)
          }
      }

    })
    }
  },

    beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.report = to.meta.report
                  v.content = to.meta.content
                  v.newClasses = to.meta.newClasses
                  v.staffIncome = to.meta.staffIncome
                  v.finance = to.meta.finance
                  v.summary = to.meta.summary
                  to.meta.report = undefined
                  to.meta.content = undefined
                  to.meta.newClasses = undefined
                  to.meta.staffIncome = undefined
                  to.meta.finance = undefined
                  to.meta.summary = undefined
                })
            }
            else{
                next()
            }
            next()

        },
        beforeRouteLeave(to,from,next){
          if (this.$route.query.id == undefined) {
            from.meta.keep = true
            from.meta.report = this.report
            from.meta.content = this.content
                  from.meta.newClasses = this.newClasses
                  from.meta.staffIncome = this.staffIncome
                  from.meta.finance = this.finance
                  from.meta.summary = this.summary
          }
          if (this.refresh){
            to.meta.refresh = 'a'
          }

          next()
        },


  created() {
    this.school = this.info.school[0]._id
    this.staff = this.info.staff == undefined ? null : this.info.staff._id
    this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
    this.school = this.info.school[0]._id
    this.report.staff.name = this.staffname
    this.report.staff._id = this.staff
    this.report.year = new Date().getFullYear()
    this.report.month = new Date().getMonth() + 1
    this.content = [{name:'团队目标',content:['','','']},{name:'出勤率',content:['','','']},{name:'续报率',content:['','','']},{name:'招生',content:['','','']}]
    if (this.$route.query.id) {
      this.disabled = true;
      this.id = this.$route.query.id
      this.getReportOne(this.id)
    } else {
      this.loadData()
    }

    
  }
};
</script>
